#!/bin/bash
### BEGIN INIT INFO
# Provides:          cyg.com.cn
# Required-Start:    $local_fs $network
# Required-Stop:     $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: cyroutr service
# Description:       cyroutr service daemon
### END INIT INFO
### --20220121

BASEDIR=/
EXEC=$BASEDIR/cyroutr

cd $BASEDIR


statusServer() {
    ROUTR_PID=$(ps -ef | grep "cyroutr" | grep -v grep | awk -F" " '{print $2}')
    ROUTR_COUNT=$(ps -ef | grep "cyroutr" | grep -v grep | awk -F" " '{print $8}' | grep cyroutr | grep -v grep | wc -l)
}

startServer() {
    statusServer
    if  [ "${ROUTR_PID}" > "0" ];then
        echo "ROUTR is is running for(pid ${ROUTR_PID}), you must stopped the cyroutr server"
        exist 1
    elif  [ "${ROUTR_COUNT}" = "0" ]; then
        echo "cyroutr is exception for(pid ${ROUTR_PID})........."
        for pid in ${ROUTR_PID[*]};do
            echo "kill cyroutr for pid $pid"
            kill -9 "${pid}"
        done
        echo "Starting cyroutr server now..."
        $EXEC
    else
        echo "Starting cyroutr server now..."
        $EXEC
    fi
}
stopServer() {
    statusServer
    echo "Stopping ..."

    echo "cyroutr is exception for(pid ${ROUTR_PID})........."
    for i in 1 2 3
    do
        echo "cyroutr stopped"
        for pid in ${ROUTR_PID[*]};do
            echo "kill cyroutr for pid $pid"
            kill -9 "${pid}"
        done
        echo "Waiting for cyroutr to shutdown ...$i"
        sleep 1
        statusServer
        if [ "${ROUTR_COUNT}" = "0" ];then
          exit 1
        fi

    done
}

case "$1" in
    start)
        startServer
        ;;
    stop)
        stopServer
        ;;
    restart)
        stopServer
        startServer
        ;;
    status)
        statusServer
        if [ ${ROUTR_COUNT} -gt 0 ];then
            echo "cyroutr is running(pid ${ROUTR_PID})"
        else
            echo "cyroutr is not running"
        fi
        ;;                       
    *)
        echo "Please use argument for( start | stop | restart | status )"
        ;;
esac
